package net.cruciblesoftware.embers;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;

import java.util.ArrayList;


class Scene {
    private static Scene instance;
    private long maxAge;
    Paint paint = new Paint();
    
    private class Particle {
        int x, y;
        long age;
    };
    private ArrayList<Particle> particles;

    public static Scene getInstance() {
        if(instance == null)
            instance = new Scene();
        return instance;
    }

    private Scene() {
        Log.i("SCENE", "creating scene");
        particles = new ArrayList<Particle>(512);
        Log.i("SCENE", "allocated " + particles.size() + " particles...");
        maxAge = (long)Settings.getInt("particle_max_age");
    }

    public synchronized void addParticle(float x, float y, long time) {
        boolean needNew = true;
        for(Particle p : particles) {
            if(p.age <= 0) {
                p.x = (int)x;
                p.y = (int)y;
                p.age = maxAge; // - (System.currentTimeMillis() - time);
                needNew = false;
                break;
            }
        }
        if(needNew) {
            Particle p = new Particle();
            p.x = (int)x;
            p.y = (int)y;
            p.age = maxAge; // - (System.currentTimeMillis() - time);
            particles.add(p);
        }
    }

    public synchronized void update(long elapsed) {
        // age the current particles
        for(Particle p : particles) {
            if(p.age > 0) {
                p.age -= elapsed;
            }
        }
    }

    public synchronized void draw(Canvas c) {
        c.drawColor(Color.BLACK);
        float grey;
        int nParts = 0;
        for(Particle p : particles) {
            if(p.age > 0.0f) {
                grey = ((float)p.age / (float)maxAge) * 255.0f;
                paint.setARGB(255, (int)grey, (int)grey, (int)grey);
                c.drawPoint(p.x, p.y, paint);
                nParts++;
            }
        }
        //Log.i("SCENE", "drew " + nParts + " of " + particles.size() + " particles");
    }
}
